# -*- coding: UTF-8 -*-

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import BoundedNumericProperty, StringProperty
from kivy.logger import Logger

from model.gamestate import Phase, Player, Word, \
    Players, Hat, TraditionalStrategy, OddStrategy

from model.dictionary import Dictionary
import model.gamestate

from constants import DEFAULTS, STEPS, BOUNDS, LABELS, DEFAULT_NAMES
from ui.hat_widget import HatWidget
from ui.settings_field import SettingField
from random import randrange
import codecs


class QuickGameSettings(HatWidget):
    PROPS = {}
    AVALIABLE_PROPS = {Phase.QUICK_GAME_SETTINGS: ('time', 'words', 'players'),
                       Phase.GAME_CONFIG: ('time', 'words', 'rounds')}

    def __init__(self, gamestate, presenter, **kwargs):
        """Making display with game settings

        need:
            gamestate.settings(if != None)
        do:
            change settings.time_per_round_sec
            & settings.words_number
        args:
            gamestate: GameState
            presenter: Presenter
        """
        super(QuickGameSettings, self).__init__(presenter, **kwargs)
        self.gamestate = gamestate
        self.gamestate.hat = Hat([])
        self.gamestate.players = Players([])
        defaults = self.presenter.settings.quick_game
        DEFAULTS['time'] = defaults.def_time_sec
        DEFAULTS['words'] = defaults.def_words_per_player
        DEFAULTS['players'] = defaults.def_players
        prev_widget = None
        with codecs.open(DEFAULT_NAMES,
                         encoding='utf-8', mode='r') as file:
            self.names = map(unicode, file.read().split('\n'))
        for k in self.AVALIABLE_PROPS[self.gamestate.phase]:
            cur = SettingField(DEFAULTS[k], BOUNDS[k][0], BOUNDS[k][1],
                               STEPS[k], _(LABELS[k]), self)
            if prev_widget is not None:
                prev_widget.bind(on_validate=cur.set_focus)
            prev_widget = cur
            self.PROPS[k] = cur
            self.settings_frame.add_widget(cur)
        prev_widget.bind(on_validate=self.next_view)

    def next_view(self, *args):
        """Changes phase to FROM_TO

        call on release "Далее" button
        """
        self.added = []
        dict_ = Dictionary.get_dict(None)
        for k, v in self.PROPS.items():
            v.read_property(v.inp)
        for i in range(self.PROPS['players'].prop):
            count = self.PROPS['words'].prop
            l = dict_.get_words(count, self.added)
            name = randrange(len(self.names))
            self.gamestate.players.add(
                Player(self.names[name].strip(), []))
            del(self.names[name])

            for j in range(len(l)):
                self.gamestate.players.players[-1].add_word(
                    Word(self.gamestate.players.players[-1], l[j]))
                self.gamestate.hat.add_word(
                    Word(self.gamestate.players.players[-1], l[j]))
                self.added.append(l[j])

        if (len(self.gamestate.players.players) % 2 == 0):
            self.gamestate.players.set_next_pair_strategy(
                TraditionalStrategy(self.gamestate.players.players))
        else:
            self.gamestate.players.set_next_pair_strategy(
                OddStrategy(self.gamestate.players.players))

        self.gamestate.settings = model.gamestate.Settings(self.PROPS['words'].
                                                           prop,
                                                           self.PROPS['time'].
                                                           prop)
        self.presenter.change_phase(Phase.EDIT_PLAYERS)

    def go_back(self):
        self.gamestate.clear()
        self.presenter.change_phase(Phase.WELCOME)
